package com.cyzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyzy.mapper.TeachersMapper;
import com.cyzy.pojo.User;
import com.cyzy.service.EmailService;
import com.cyzy.service.TeachersService;
import com.cyzy.utils.SHA256Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class TeachersServiceImpl implements TeachersService {

    @Autowired
    private TeachersMapper teacherMapper;

    @Autowired
    private EmailService emailService;

    private Random random = new Random();

    @Override
    public User login(String userAcc, String userPwd) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 确保查询包含campus_id字段，MyBatis-Plus会自动映射到campusId属性
        queryWrapper.select(
                        "user_id", "user_acc", "user_pwd", "user_name", "user_sex", "user_phone",
                        "user_email", "user_status", "last_login_time", "create_time", "campus_id",
                        "user_note", "avatar_frame_url"
                )
                .eq("user_acc", userAcc)
                .eq("user_pwd", userPwd)
                .eq("user_status", "0")
                .like("user_note", "教师")
                .eq("user_type", 5);

        return teacherMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean forgotPassword(String userAcc, String userEmail) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_acc", userAcc)
                .eq("user_email", userEmail)
                .like("user_note", "教师")
                .eq("user_type", 5);

        User teacher = teacherMapper.selectOne(queryWrapper);
        if (teacher == null) {
            return false;
        }

        // 生成随机密码
        int newPassword = 100000 + random.nextInt(900000);
        String encryptedPassword = SHA256Utils.encryptPassword(String.valueOf(newPassword));

        // 更新密码
        teacher.setUserPwd(encryptedPassword);
        int result = teacherMapper.updateById(teacher);

        if (result > 0) {
            // 发送邮件
            String subject = "教师系统密码重置通知";
            String text = "尊敬的教师用户：\n\n您的密码已重置为：" + newPassword +
                    "\n\n请及时登录系统修改密码。";

            emailService.sendSimpleEmail(userEmail, subject, text);
            return true;
        }

        return false;
    }

    @Override
    public boolean updateProfile(User user) {
        // 获取现有用户信息
        User existingUser = teacherMapper.selectById(user.getUserId());
        if (existingUser == null) {
            return false;
        }

        // 更新允许修改的字段（包括头像URL）
        existingUser.setUserName(user.getUserName());
        existingUser.setUserSex(user.getUserSex());
        existingUser.setUserPhone(user.getUserPhone());
        existingUser.setUserEmail(user.getUserEmail());
        existingUser.setUserNote(user.getUserNote());

        // **新增：处理头像更新（直接使用传入的avatarFrameUrl）**
        if (user.getAvatarFrameUrl() != null && !user.getAvatarFrameUrl().isEmpty()) {
            existingUser.setAvatarFrameUrl(user.getAvatarFrameUrl());
        }

        // 执行更新
        int result = teacherMapper.updateById(existingUser);
        return result > 0;
    }

    // 新增方法实现
    @Override
    public User getUserById(Long userId) {
        return teacherMapper.selectById(userId);
    }

}